package com.cdqidi.core.weixinmanager.service.wx;

import com.cdqidi.constant.ConstantDto;
import com.cdqidi.core.weixinmanager.model.OrgWxConfig;
import com.cdqidi.core.weixinmanager.model.UserInfo;
import com.cdqidi.core.weixinmanager.service.OrgWxConfigService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author sjk
 * @create 2019-09-11 11:38
 * @since 1.0.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WxMsgService {
    private final ObjectMapper objectMapper;
    private final WxApiService wxApiService;
    private final OrgWxConfigService orgWxConfigService;
    public static final String SUBSCRIBE = "subscribe";


    @Transactional(rollbackFor = Exception.class)
    public OutTextMsg saveWxUserInfo(InFollowEvent inFollowEvent) {
        OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
        String event = inFollowEvent.getEvent();
        final OrgWxConfig wxConfig = orgWxConfigService.getById(ApiConfigKit.getAppId());
        //关注
        buildDb(inFollowEvent, wxConfig);
        String msg;
        if (event.equals(SUBSCRIBE)) {
            msg = "感谢关注";
        } else {
            msg = "取消关注";
        }
        outMsg.setContent(msg);
        return outMsg;
    }

    @SneakyThrows
    private void buildDb(InFollowEvent inFollowEvent, OrgWxConfig wxConfig) {

        ApiResult result = UserApi.getUserInfo(inFollowEvent.getFromUserName());
        if (!result.isSucceed()) {
            log.info("appId: {},wxConfig: {}", ApiConfigKit.getAppId(), objectMapper.writeValueAsString(wxConfig));
            log.info("toUserName: {},result: {}", inFollowEvent.getFromUserName(), result.getJson());
            return;
        }
        UserInfo userInfo;
        if (inFollowEvent.getEvent().equals(SUBSCRIBE)) {
            userInfo = wxApiService.saveWxUserInfo(result, wxConfig.getAppId(), ConstantDto.SF1);
        } else {
            userInfo = wxApiService.updateWxUserInfo(result, inFollowEvent.getCreateTime().longValue(), ConstantDto.SF0);
        }
        Optional.ofNullable(userInfo).ifPresent(UserInfo::freeData);
    }
}